// ignore_for_file: must_be_immutable

import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

typedef ConfirmCallback = void Function(List data, Map selectData);

class MapPickerMore extends StatefulWidget {
  List dataList;
  // 默认150.w
  double itemPickerWidth;
  // 显示的字段名称
  String name;
  // 子目录名称
  String children;

  ConfirmCallback? confirmCallback;
  Function? onCancel;

  // 横屏
  bool isLandscape;

  // 是否要选择详细数据（最后的层级）
  bool isSelectDetail;

  String? titleText;
  Color? titleTextColor;

  MapPickerMore(
    this.dataList,
    this.name,
    this.children,
    this.itemPickerWidth,
    this.confirmCallback,
    this.onCancel,
    this.isLandscape,
    this.isSelectDetail,
    this.titleText,
    this.titleTextColor, {
    Key? key,
  }) : super(
          key: key,
        );

  @override
  _MapPickerMoreState createState() => _MapPickerMoreState();
}

class _MapPickerMoreState extends State<MapPickerMore>
    with WidgetsBindingObserver {
  final WidgetsBinding widgetsBinding = WidgetsBinding.instance;
  Map showDataMap = {};
  List<Widget> cupertinoPickerList = [];
  List selectList = [];
  double keyboardHeight = 0;
  String hintData = '暂无数据';
  PageController pageController = PageController();
  int pageIndex = 0;

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    widgetsBinding.addPersistentFrameCallback(
      (_) {
        if (mounted) {
          if (MediaQuery.of(context).viewInsets.bottom == 0) {
            // 关闭键盘
            keyboardHeight = 0;
          } else {
            // 打开键盘
            // 键盘高度
            keyboardHeight = EdgeInsets.fromWindowPadding(
                    widgetsBinding.window.viewInsets,
                    widgetsBinding.window.devicePixelRatio)
                .bottom;
          }

          setState(() {});
        }
      },
    );
  }

  @override
  void initState() {
    // 初始化监听页面高度
    widgetsBinding.addObserver(this);
    initData();
    super.initState();
  }

  initData() async {
    String json = jsonEncode({widget.children: widget.dataList});
    showDataMap = jsonDecode(json);
    makeViewData(showDataMap);
    setState(() {});
  }

  @override
  void dispose() {
    widgetsBinding.removeObserver(this);
    super.dispose();
  }

  makeViewData(Map itemData) {
    if (itemData[widget.children] != null &&
        itemData[widget.children].isNotEmpty) {
      if (itemData['cupertinoPickerIndex'] == null) {
        itemData['cupertinoPickerIndex'] = 0;
      }
      selectList
          .add(itemData[widget.children][itemData['cupertinoPickerIndex']]);
      List<Widget> itemList = [];
      for (Map item in itemData[widget.children]) {
        itemList.add(
          Container(
            width: widget.itemPickerWidth,
            height: 60.w,
            padding: EdgeInsets.symmetric(horizontal: 10.w),
            alignment: Alignment.center,
            child: Text(
              item[widget.name],
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: widget.isLandscape ? 8.w : 16.w,
              ),
            ),
          ),
        );
      }
      cupertinoPickerList.add(
        CupertinoPicker(
          scrollController: FixedExtentScrollController(
              initialItem: itemData['cupertinoPickerIndex']),
          backgroundColor: Colors.white, //选择器背景色
          itemExtent: 60.w, //item的高度
          onSelectedItemChanged: (selectedIndex) {
            itemData['cupertinoPickerIndex'] = selectedIndex;
            cupertinoPickerList = [];
            selectList = [];
            makeViewData(showDataMap);
            setState(() {});
          },
          children: itemList,
        ),
      );
      makeViewData(itemData[widget.children][itemData['cupertinoPickerIndex']]);
      setState(() {});
    }
    setState(() {});
  }

  Map makeSearchData(Map itemData, String value) {
    if (itemData[widget.children] != null &&
        itemData[widget.children].isNotEmpty) {
      List tempList = [];
      for (Map item in itemData[widget.children]) {
        Map data = makeSearchData(item, value);
        if (data.isNotEmpty) {
          tempList.add(data);
        }
      }
      if (tempList.isEmpty) {
        return {};
      }
      itemData[widget.children] = tempList;
      return itemData;
    } else {
      if (itemData[widget.name] != null &&
          itemData[widget.name].contains(value)) {
        return itemData;
      } else {
        return {};
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: InkWell(
        onTap: () {
          FocusManager.instance.primaryFocus?.unfocus();
        },
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Expanded(
              child: InkWell(
                onTap: () {
                  if (keyboardHeight == 0) {
                    Navigator.pop(context);
                  } else {
                    FocusManager.instance.primaryFocus?.unfocus();
                  }
                },
                child: Container(),
              ),
            ),
            Container(
              color: Colors.white,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  InkWell(
                    onTap: () {
                      Navigator.pop(context);
                      if (widget.onCancel != null) {
                        widget.onCancel!();
                      }
                    },
                    child: Container(
                      color: Colors.white,
                      padding: EdgeInsets.only(
                          top: 5.w, left: 15.w, bottom: 5.w, right: 5.w),
                      child: Text(
                        '取消',
                        style: TextStyle(
                            color: Colors.black,
                            fontSize: widget.isLandscape ? 8.w : 16.w),
                      ),
                    ),
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      widget.titleText == null
                          ? Container()
                          : Container(
                              margin: EdgeInsets.only(top: 5.w),
                              alignment: Alignment.center,
                              color: Colors.white,
                              width: widget.isLandscape ? 120.w : 150.w,
                              child: Text(
                                widget.titleText ?? '',
                                style: TextStyle(
                                    fontWeight: FontWeight.w700,
                                    color:
                                        widget.titleTextColor ?? Colors.black,
                                    fontSize: widget.isLandscape ? 8.w : 16.w),
                              ),
                            ),
                      Container(
                        alignment: Alignment.center,
                        width: widget.isLandscape ? 120.w : 150.w,
                        decoration: BoxDecoration(
                            color: Colors.white60,
                            border:
                                Border.all(color: Colors.white60, width: 0.5.w),
                            borderRadius: BorderRadius.circular((20.w))),
                        child: TextField(
                          style: TextStyle(
                              color: Colors.black,
                              fontSize: widget.isLandscape ? 8.w : 16.w),
                          textAlign: TextAlign.center,
                          decoration: InputDecoration(
                              hintText: "请输入搜索内容",
                              hintStyle: TextStyle(
                                  fontSize: widget.isLandscape ? 8.w : 16.w),
                              contentPadding:
                                  EdgeInsets.only(top: 4.w, left: 10.w),
                              border: InputBorder.none),
                          onChanged: (String value) {
                            hintData = '加载中...';
                            Future.delayed(const Duration(milliseconds: 50),
                                () async {
                              String json = jsonEncode(
                                  {widget.children: widget.dataList});
                              Map searchData =
                                  makeSearchData(jsonDecode(json), value);
                              showDataMap = searchData;
                              cupertinoPickerList = [];
                              selectList = [];
                              //延时执行
                              Future.delayed(const Duration(milliseconds: 50),
                                  () async {
                                makeViewData(searchData);
                                hintData = '暂无数据';
                                setState(() {});
                              });
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                  InkWell(
                    onTap: () {
                      if (isShowSure()) {
                        Navigator.pop(context);
                        for (Map item in selectList) {
                          item.remove(widget.children);
                        }
                        if (widget.confirmCallback != null) {
                          widget.confirmCallback!(
                              selectList, selectList[pageIndex]);
                        }
                      }
                    },
                    child: Container(
                      color: Colors.white,
                      padding: EdgeInsets.only(
                          top: 5.w, left: 5.w, bottom: 5.w, right: 15.w),
                      child: Text(
                        '确定',
                        style: TextStyle(
                            color: isShowSure()
                                ? Colors.black
                                : Colors.transparent,
                            fontSize: widget.isLandscape ? 8.w : 16.w),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            cupertinoPickerList.isEmpty
                ? Container(
                    alignment: Alignment.center,
                    height: widget.isLandscape ? 110.w : 200.w,
                    width: MediaQuery.of(context).size.width,
                    color: Colors.white,
                    child: Text(hintData),
                  )
                : Container(
                    width: MediaQuery.of(context).size.width,
                    height: widget.isLandscape ? 110.w : 200.w,
                    alignment: Alignment.center,
                    color: Colors.white,
                    child: PageView.builder(
                      itemBuilder: (context, index) {
                        return Stack(
                          alignment: Alignment.center,
                          children: [
                            cupertinoPickerList[index],
                            (index == 0)
                                ? Container()
                                : Positioned(
                                    left: 10.w,
                                    child: InkWell(
                                      onTap: () {
                                        pageController.jumpToPage(index - 1);
                                        setState(() {});
                                      },
                                      child: Icon(Icons.keyboard_arrow_left,
                                          size:
                                              widget.isLandscape ? 15.w : 30.w,
                                          color: Colors.grey),
                                    ),
                                  ),
                            (index == cupertinoPickerList.length - 1)
                                ? Container()
                                : Positioned(
                                    right: 10.w,
                                    child: InkWell(
                                      onTap: () {
                                        pageController.jumpToPage(index + 1);
                                      },
                                      child: Icon(Icons.keyboard_arrow_right,
                                          size:
                                              widget.isLandscape ? 15.w : 30.w,
                                          color: Colors.grey),
                                    ),
                                  ),
                          ],
                        );
                      },
                      itemCount: cupertinoPickerList.length, //页面数量
                      onPageChanged: (int value) {
                        pageIndex = value;
                        setState(() {});
                      }, //页面切换
                      controller: pageController, //控制器
                    ),
                  ),
            SizedBox(height: widget.isLandscape ? 0.w : keyboardHeight),
          ],
        ),
      ),
    );
  }

  bool isShowSure() {
    if (widget.isSelectDetail) {
      if (cupertinoPickerList.length - 1 == pageIndex) {
        return true;
      } else {
        return false;
      }
    } else {
      return true;
    }
  }
}
